var data = require("./data.js");
var clickjs = require("./click.js");
var mousejs = require("./mouse.js");

var define = data.define;

var bombs = [];

function createBoom(map, mapW, mapH, width, mapMouse) {
  if (!clickjs.canInput(map, mapW, mapH, width, mapMouse))
    return;

  var t = {};
  t.x = parseInt(clickjs.getX());
  t.y = parseInt(clickjs.getY());
  t.times = 0;
  t.sx = parseInt(Math.max(t.x - define.BombWidth / 2, 1));
  t.sy = parseInt(Math.max(t.y - define.BombWidth / 2, 1));
  t.ex = Math.min(t.sx + define.BombWidth, mapH - 2);
  t.ey = Math.min(t.sy + define.BombWidth, mapW - 2);
  bombs.push(t);
  showBoom(t, map, mapW, mapH, width, mapMouse);
}

function draw_bombFlash(b, map, mapW, mapH, width, mapMouse) {
  for (var i = b.sx; i <= b.ex; i++) {
    for (var j = b.sy; j <= b.ey; j++) {
      if (!data.isWall(map[i][j]) && map[i][j] != define.Block) {
        if (b.times % 2 == 0)
          map[i][j] = define.BombFlash;
        else
          map[i][j] = 0;
      }
    }
  }
}

function showBoom(b, map, mapW, mapH, width, mapMouse) {
  map[b.x][b.y] = define.BOMB;
}

function clearBoom(b, map, mapW, mapH, width, mapMouse) {
  for (var i = b.sx; i <= b.ex; i++) {
    for (var j = b.sy; j <= b.ey; j++) {
      if (map[i][j] == define.BombFlash) {
        map[i][j] = 0;
      }
    }
  }
}

function detectMouse(b, map, mapW, mapH, width, mapMouse) {
  for (var i = b.sx; i <= b.ex; i++) {
    for (var j = b.sy; j <= b.ey; j++) {
      if (mapMouse[i][j] != -1) {
        mousejs.delete_mouse(mapMouse[i][j], map, mapW, mapH, width, mapMouse);
        console.log("bombs: mouse!")
      }
    }
  }
}

function updateBooms(map, mapW, mapH, width, mapMouse) {
  var temp = [];
  for (var i = 0; i < bombs.length; i++) {
    bombs[i].times++;
    if (bombs[i].times <= (define.WapBombTime + define.BombFlashTime) / define.ShowDelay) {
      if (bombs[i].times >= define.WapBombTime / define.ShowDelay) {
        detectMouse(bombs[i], map, mapW, mapH, width, mapMouse);
        draw_bombFlash(bombs[i], map, mapW, mapH, width, mapMouse);
      }
      else
        showBoom(bombs[i], map, mapW, mapH, width, mapMouse);
      temp.push(bombs[i]);
    }
    else {
      clearBoom(bombs[i], map, mapW, mapH, width, mapMouse);
    }
  }
  bombs = temp;
}

function getNum() {
  return bombs.length;
}

function clear() {
  bombs = []
}

function getInfo(map){
  let temp = [];
  for(var n=0;n<bombs.length;n++)
  {
    var b=bombs[n];
    for (var i = b.sx; i <= b.ex; i++) {
      for (var j = b.sy; j <= b.ey; j++) {
        if (map[i][j] == define.BombFlash || map[i][j] == define.BOMB) 
        {
          var t={};
          t.x=i;
          t.y=j;
          temp.push(t);
        }
      }
    }
  }
  return temp;
}
module.exports = {
  createBoom: createBoom,
  updateBooms: updateBooms,
  getNum: getNum,
  clear: clear,
  getInfo:getInfo
}